<template>
	<view class="content" @click="showHouseSelector = false">
		<uni-nav-bar class="custom-nav-bar" fixed status-bar title="首页">
			<view slot="left" class="common left">
				<view class="location" v-if="houselist.length" @click.stop="toggleHouseSelector(true)">
					<text class="city-name">{{ currentHouse.projectName || (houselist[0] ? houselist[0].projectName : '请选择房屋') }}</text>
					<image
						src="//mall-rongchuang.oss-cn-beijing.aliyuncs.com/guixin_miniProgram/img/position_select.png"
						@click.stop="toggleHouseSelector(true)"
						style="width: 10rpx;height: 8rpx;"
					></image>
				</view>
				<view class="location" v-else>
					<text class="city-name" @click.stop="toggleHouseSelector(false)">{{ location.cityName || '' }}</text>
					<uni-icons type="arrowdown" size="14" @click.stop="toggleHouseSelector(false)"></uni-icons>
				</view>
			</view>
		</uni-nav-bar>
		<home ref="home"></home>
		<house-picker :visible.sync="showHouseSelector" :dataSource="houselist" @addHouse="addHouse" class="house-select" />
	</view>
</template>

<script>
import http, { customUrl } from '../../common/request.js';
import Home from './home.vue';
import housePicker from './house-picker.vue';
import { mapState } from 'vuex';
import { getLocationHref, getWxShareHref, getCommonShareInfo } from '../../common/utils.js';
export default {
	computed: {
		...mapState({
			list: state => state.houseSetting.houseList,
			userInfo: state => state.userInfo,
			location: state => state.location,
			currentHouse: state => state.currentHouse
		})
	},
	components: {
		housePicker,
		Home
	},
	onLoad(option) {
		let code = decodeURIComponent(option.scene || ''); // 扫描小程序获得内容
		this.$store.commit('STORE_SCENE', code);

		const userSource = option.userSource || '';
		if (userSource) {
			this.$store.commit('STORE_USERSOURCE', userSource);
		}
	},
	data() {
		return {
			selected: [],
			houselist: [],
			// list: [],
			showHouseSelector: false,
			showList: false
		};
	},
	onPullDownRefresh() {
		this.$refs.home.getAllRequest();
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 1000);
	},
	mounted(options) {
		this.getList();
	},
	onShow() {
		this.$nextTick(() => {
			if (this.$refs.home) {
				this.$refs.home.getAllRequest();
			}
		});
	},
	async onShareAppMessage(res) {
		if (res.from === 'menu') {
			return getCommonShareInfo();
		} else {
			const { title, path, imageUrl } = await this.$refs.home.getSharePhoto();
			return {
				title,
				path,
				imageUrl
			};
		}
	},
	//监听页面滚动
	onPageScroll(res) {
		this.$refs.home.scrollTop = res.scrollTop;
	},
	methods: {
		toggleHouseSelector(tag) {
			if (tag) {
				//埋点
				this.$umaTrackEvent('showHouseList', { source: '首页' });
				this.showHouseSelector = true;
			} else {
				//埋点
				this.$umaTrackEvent('selectHouse', { source: '首页' });
				uni.navigateTo({
					url: '../../houseSetting/index',
					animationType: 'pop-in',
					animationDuration: 200
				});
				// this.showList = true;
			}
		},
		getList() {
			http('/api/mdmCustomerRoom/getProjectList', {
				method: 'GET'
			}).then(result => {
				if (result.code === 200) {
					const list = result.data || [],
						roomIds = [];
					// for (let item of list) {
					// 	if (item.status !== 1 && item.status !== 3) {
					// 		roomIds.push(item.roomId);
					// 	}
					// }

					// for (let item of list) {
					// 	if (!item.status) {
					// 		this.houselist.push(item);
					// 	}
					// }
					for (let item of list) {
						if (item.status === '1') {
							roomIds.push(item.roomId);
							this.houselist.push(item);
						}
					}
					this.houselist = this.deWeightFour(this.houselist);

					this.$store.dispatch('houseSetting/updateHouseList', list);
					this.$store.dispatch('houseSetting/updateRoomIds', roomIds);
					const userInfo = this.userInfo;
					if (userInfo && userInfo.userId) {
						//获取历史地理位置，不需要经纬度
						this.$store
							.dispatch('getLocationByGPS', {
								latitude: '',
								longitude: ''
							})
							.then(result => {
								if (!result) {
									// #ifdef MP-WEIXIN
									authorTodo({
										type: 'userLocation',
										success: () => {
											// #endif
											uni.getLocation({
												type: 'gcj02',
												success: res => {
													this.$store.dispatch('getLocationByGPS', res);
												}
											});
											// #ifdef MP-WEIXIN
										}
									});
									// #endif
								}
							});
					}
				}
			});
		},
		deWeightFour(arr4) {
			let obj = {};
			arr4 = arr4.reduce(function(a, b) {
				obj[b.projectName] ? '' : (obj[b.projectName] = true && a.push(b));
				return a;
			}, []);
			return arr4;
		},
		addHouse() {
			http('/api/mdmCustomerRoom/getToken', {
				method: 'GET'
			}).then(res => {
				if (res.code === 200) {
					const token = res.data.accessToken || '';
					let params = `token=${token}`;
					const location = uni.getStorageSync('location');
					if (location) {
						params += `&adcode=${location.cityCode}&cityName=${location.cityName}`;
					}
					const url = `${customUrl.bindHouseHost}/h5/myHouse/myHouse?${params}`;
					uni.navigateTo({
						url: `../../home/web_view?url=${encodeURIComponent(url)}`,
						animationType: 'pop-in',
						animationDuration: 200
					});
				}
			});
		},
		goToSelectCity() {
			uni.navigateTo({
				url: '../../houseSetting/index',
				animationType: 'pop-in',
				animationDuration: 200
			});
		}
	}
};
</script>
<style lang="less" scoped>
.location {
	// max-width: 200rpx;
	height: 50rpx;
	background: rgba(138, 140, 141, 0.1);
	border-radius: 25rpx;
	line-height: 1;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 18rpx;
	font-size: 24rpx;
	color: #66645d;
	position: relative;
	.city-name {
		margin-right: 6rpx;
		white-space: nowrap;
		text-overflow: ellipsis;
		// overflow: hidden;
		// max-width: 120px;
		margin-left: 8px;
		// width: 120rpx;
	}
	image {
		position: absolute;
		top: 20rpx;
	}
}

.house-select {
	position: fixed;
	/* #ifdef MP-WEIXIN */
	top: 108rpx;
	/* #endif */
	/* #ifndef MP-WEIXIN */
	top: 70rpx;
	/* #endif */
	left: 20rpx;
	z-index: 100;
	background: #fff;
	min-width: 240rpx;
	max-width: 320rpx;
	border-radius: 0rpx 0rpx 24rpx 24rpx;
}
</style>
